package com.br.android.widing.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.br.android.widing.R;

public class WidingDataBase extends SQLiteOpenHelper {

	private static final String DATABASE_NAME = "widing.db";

	private static final int DATABASE_VERSION = 8;

	private Context mContext;

	public WidingDataBase(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.mContext = context;

	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String[] sql = mContext.getString(R.string.sql_create_tables).split(
				"\\|");
		for (int i = 0; i < sql.length; i++) {
			Log.i("SQL: ", sql[i]);
		}
		db.beginTransaction();
		try {
			// cria tabela e testa dados
			execMultipleSQL(db, sql);
			db.setTransactionSuccessful();
		} catch (Exception e) {
			Log.e("Erro ao criar tabelas e dados de depura̤̣o", e.getMessage());
		} finally {
			db.endTransaction();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		String[] sql = mContext.getString(R.string.sql_upgrade_tables).split(
				"\\|");
		for (int i = 0; i < sql.length; i++) {
			Log.i("SQL: ", sql[i]);
		}
		db.beginTransaction();
		try {
			execMultipleSQL(db, sql);
			db.setTransactionSuccessful();
		} catch (Exception e) {
			Log.e("Erro ao atualizar tabela", e.getMessage());
		} finally {
			db.endTransaction();
		}
	}

	private void execMultipleSQL(SQLiteDatabase db, String[] sql) {
		for (String s : sql) {
			if (s.trim().length() > 0) {
				db.execSQL(s);
			}
		}
	}

}
